package com.shanjige.chatgpt.chatgptweb.web;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.shanjige.chatgpt.chatgptweb.common.ResultBase;
import com.shanjige.chatgpt.chatgptweb.dto.ResultDTO;
import com.shanjige.chatgpt.chatgptweb.request.GetMessageReq;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author qhong
 * @date 2023/2/7 18:16
 **/
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("")
public class IndexController {


    @RequestMapping(value = "/", method = {RequestMethod.POST})
    public ResultBase<ResultDTO> getMessage(@RequestBody @Validated GetMessageReq request) {
        List<String> tokens = Arrays.asList("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",
            "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");
        Map<String,String> headers = new HashMap<>(8);
        headers.put("Content-Type","application/json;charset=UTF-8");

        JSONObject json = new JSONObject();
        //选择模型
        json.set("model","text-davinci-003");
        //添加我们需要输入的内容
        json.set("prompt",request.getMessage());
        json.set("temperature",0.9);
        json.set("max_tokens",2048);
        json.set("top_p",1);
        json.set("frequency_penalty",0.0);
        json.set("presence_penalty",0.6);

        log.info("start");
        String token = tokens.get(new Random().nextInt(tokens.size()));
        log.info("token:{}", token);

        HttpResponse response = HttpRequest.post("https://api.openai.com/v1/completions")
            .headerMap(headers, false)
            .bearerAuth(token)
            .body(String.valueOf(json))
            .timeout(5 * 60 * 1000)
            .execute();


        log.info("body:{}",response.body());

        com.alibaba.fastjson.JSONArray result = com.alibaba.fastjson.JSONObject.parseObject(response.body()).getJSONArray("choices");
        if(result.isEmpty()){
            String errMsg =
                com.alibaba.fastjson.JSONObject.parseObject(response.body()).getJSONObject("error").get("message").toString();
            log.info("errMsg:{}", errMsg);
            return ResultBase.getErrorResult(errMsg);
        }
        log.info("result:{}", JSON.toJSONString(result));
        return ResultBase.getSuccessResult(ResultDTO.of().setResult(result));
    }

}
